package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * TODO
     *      - 上传素材图片
     *
     * @param file MultipartFile
     * @return ResponseResult
     */
    public ResponseResult uploadPicture(MultipartFile file) {
        // 1.校验参数
        if (file == null || file.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "图片参数无效");
        }
        // 2.上传图片到minio，返回图片地址
        String originalFilename = file.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuid + postfix;
        String filePath = null;
        try {
            filePath = fileStorageService.uploadImgFile("", fileName, file.getInputStream());
            log.info("上传图片到MinIO中，filePath:{}", filePath);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
        }
        // 3.保存到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(filePath);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        // 4.返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * TODO
     *      - 分页显示素材列表
     *
     * @param dto WmMaterialDto
     * @return ResponseResult
     */
    @Override
    public ResponseResult findAll(WmMaterialDto dto) {
        // 1.校验参数
        dto.checkParam();
        // 2.设置分页
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        // 3.设置查询条件
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        // 如果是收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, 1);
        }
        page(page, wrapper);
        // 4.封装分页数据
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        // 5.返回结果
        return responseResult;
    }

    /**
     * TODO
     *      - 收藏素材
     *
     * @return ResponseResult
     */
    @Override
    public ResponseResult changeCollect(Integer id, Short collect) {
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmMaterial.setIsCollection(collect);
        updateById(wmMaterial);
        return ResponseResult.okResult("操作成功");
    }

    /**
     * TODO
     *      - 删除素材
     *
     * @param id 素材id
     * @return ResponseResult
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        // 1.校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.查询使用当前素材的文章数
        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(
                Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        // 3.如果大于0，不可以删除，返回错误信息
        if (wmNewsMaterials.size() > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件删除失败");
        }
        // 4.否则删除素材。返回结果
        removeById(id);
        return ResponseResult.okResult("操作成功");
    }
}
